//
//  COCOAFANPmsgWindowController.m
//  CocoaFan
//
//  Created by Chen Xianan on 2009-03-29.
//  Copyright 2009 realazy.org. All rights reserved.
//

#import "COCOAFANPmsgWindowController.h"
#import "COCOAFANFormatter.h"
#import "YRKSpinningProgressIndicator.h"
#import "AppController.h"

NSString * const COCOAFANSendPmsgNotification = @"sendPmsgNotification";

@implementation COCOAFANPmsgWindowController

@synthesize statusContent, msgField, counter, tip, textColor, needsShowIndicator;

- (id)init
{
	if (![super initWithWindowNibName:@"PmsgSender"]) return nil;

	return self;
}

- (void)dealloc
{
	[timer release];
	[self setStatusContent:nil];
	[self setTip:nil];
	[self setTextColor:nil];
	[super dealloc];
}

- (void)awakeFromNib
{
	COCOAFANFormatter *formatter = [[[COCOAFANFormatter alloc] init] autorelease];
	[msgField setFormatter:formatter];
	[[self window] setTitle:NSLocalizedString(@"PMSG_WINTITLE", @"CocoaFan - Send Private Message")];
	[indicator setForeColor:[NSColor whiteColor]];
	[indicator setBackColor:[NSColor clearColor]];
}

- (IBAction)sendMessage:(id)sender
{
	NSString *val = [msgField stringValue];
	if (![val length]) return;

	[msgField setEnabled:NO];
	[self showTipWithIndicator:NSLocalizedString(@"PMSG_SENDING", "Sending...")
						  type:COCOAFAN_PMSGTIP_NORMAL];
	NSNumber *msgid;
	if ([[statusContent objectForKey:@"type"] intValue] == COCOAFAN_STATUS_PMSG)
		msgid = [statusContent objectForKey:@"id"];
	else
		msgid = [NSNumber numberWithInt:0];
	
	NSDictionary *info = [NSDictionary dictionaryWithObjectsAndKeys:
		val, @"message",
		[statusContent objectForKey:@"userid"], @"userid",
		msgid, @"in_reply_to_id", nil];
	[[NSNotificationCenter defaultCenter]
			postNotificationName:COCOAFANSendPmsgNotification
						  object:self
						userInfo:info];
}

- (IBAction)closeWindow:(id)sender
{
	[timer invalidate];
	[self close];
}

- (void)scheduledCloseWindow:(NSTimeInterval)interval
{
	timer = [[NSTimer scheduledTimerWithTimeInterval:interval
											  target:self
											selector:@selector(closeWindow:)
											userInfo:nil
											 repeats:NO] retain];
}

- (void)_showTip:(NSString *)tip_
   showIndicator:(BOOL)show
   			type:(COCOAFAN_PMSGTIP_TYPE)type
{
	NSColor *color = type == COCOAFAN_PMSGTIP_NORMAL ? [NSColor whiteColor] : [NSColor redColor];	
	[self setTextColor:color];
	[self setTip:tip_];
	[self setNeedsShowIndicator:show];
	if (show) [indicator startAnimation:self];
	else  [indicator stopAnimation:self];
}

- (void)showTip:(NSString *)tip_
		   type:(COCOAFAN_PMSGTIP_TYPE)type
{
	[self _showTip:tip_
	 showIndicator:NO
			  type:type];
}

- (void)showTipWithIndicator:(NSString *)tip_
						type:(COCOAFAN_PMSGTIP_TYPE)type
{
	[self _showTip:tip_
	 showIndicator:YES
			  type:type];
}

#pragma mark NSTextField delegate
- (void)controlTextDidChange:(NSNotification *)aNotification
{
	int num = [[msgField stringValue] length];
	[counter setIntValue:num];
}

@end
